package rahmath.sharif.docrypt;

import java.io.File;
import java.io.IOException;

import javax.crypto.Cipher;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.util.Docrypt;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class CryptFileActivity extends Activity implements DocryptConstants,
		DocryptInterface {

	private static String inputFilePath;
	private static String destinationDirectory;
	private ProgressDialog progressDialog;

	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	public Activity getActivity() {
		return this;
	}

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_crypt_file);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_crypt_file, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void chooseFile(View view) {
		Intent intentChooseFile = new Intent(this, Explorer.class);
		intentChooseFile.putExtra(INTENT_EXTRA_CHOOSE, FILE);
		try {
			intentChooseFile
					.putExtra(INTENT_EXTRA_FILE_PATH,
							inputFilePath == null ? Environment
									.getExternalStorageDirectory()
									.getCanonicalPath() : new File(
									inputFilePath).getParentFile().getPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
		startActivityForResult(intentChooseFile, INTENT_CHOOSE_FILE);
	}

	public void encrypt(View view) {
		String password = ((EditText) findViewById(R.id.editTextFilePassword))
				.getText().toString();
		String sourcePath = ((EditText) findViewById(R.id.editTextInputFile))
				.getText().toString();
		String derivedPath = ((EditText) findViewById(R.id.editTextDestinationDirectory))
				.getText().toString();
		if (null == sourcePath || null == derivedPath
				|| sourcePath.length() == 0 || derivedPath.length() == 0) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.chooseSrcDests), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		File sourceFile = new File(sourcePath);
		if (sourceFile.length() > DocryptUtil.getSpaceAvailable()) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.spaceNotAvailable), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		File derivedFile = new File(derivedPath + FILE_SEPARATOR
				+ sourceFile.getName());
		final Docrypt docrypt = new Docrypt(this, password, sourceFile,
				derivedFile, Cipher.ENCRYPT_MODE);
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(getString(R.string.encrypting));
		progressDialog.setIndeterminate(false);
		progressDialog.setMax(100);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						docrypt.cancel(true);
						dialog.dismiss();
					}
				});
		progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				return true;
			}
		});
		docrypt.execute((String[]) null);
	}

	public void decrypt(View view) {
		String password = ((EditText) findViewById(R.id.editTextFilePassword))
				.getText().toString();
		String sourcePath = ((EditText) findViewById(R.id.editTextInputFile))
				.getText().toString();
		String derivedPath = ((EditText) findViewById(R.id.editTextDestinationDirectory))
				.getText().toString();
		if (null == sourcePath || null == derivedPath
				|| sourcePath.length() == 0 || derivedPath.length() == 0) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.chooseSrcDests), Toast.LENGTH_SHORT)
					.show();
			return;
		}

		File sourceFile = new File(sourcePath);
		if (sourceFile.length() > DocryptUtil.getSpaceAvailable()) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.spaceNotAvailable), Toast.LENGTH_SHORT)
					.show();
			return;
		}
		File derivedFile = new File(derivedPath + FILE_SEPARATOR
				+ sourceFile.getName());
		final Docrypt docrypt = new Docrypt(this, password, sourceFile,
				derivedFile, Cipher.DECRYPT_MODE);
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(getString(R.string.decrypting));
		progressDialog.setIndeterminate(false);
		progressDialog.setMax(100);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						docrypt.cancel(true);
						dialog.dismiss();
					}
				});
		progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				return true;
			}
		});
		docrypt.execute((String[]) null);
	}

	public void chooseDirectory(View view) {
		Intent intentChooseFile = new Intent(this, Explorer.class);
		intentChooseFile.putExtra(INTENT_EXTRA_CHOOSE, DIRECTORY);
		try {
			intentChooseFile.putExtra(INTENT_EXTRA_FILE_PATH,
					destinationDirectory == null ? Environment
							.getExternalStorageDirectory().getCanonicalPath()
							: destinationDirectory);
		} catch (IOException e) {
			e.printStackTrace();
		}
		startActivityForResult(intentChooseFile, INTENT_CHOOSE_DIRECTORY);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case INTENT_CHOOSE_FILE:
			if (resultCode == Activity.RESULT_OK) {
				inputFilePath = data.getStringExtra(INTENT_EXTRA_CHOOSEN_PATH);
				((TextView) findViewById(R.id.editTextInputFile))
						.setText(inputFilePath);
			}
			break;
		case INTENT_CHOOSE_DIRECTORY:
			if (resultCode == Activity.RESULT_OK) {
				destinationDirectory = data
						.getStringExtra(INTENT_EXTRA_CHOOSEN_PATH);
				((TextView) findViewById(R.id.editTextDestinationDirectory))
						.setText(destinationDirectory);
			}
			break;
		}
		if (null != inputFilePath && 0 != inputFilePath.length()
				&& null != destinationDirectory
				&& 0 != destinationDirectory.length()) {
			findViewById(R.id.btnEncrypt).setEnabled(true);
			findViewById(R.id.btnDecrypt).setEnabled(true);
		} else {
			findViewById(R.id.btnEncrypt).setEnabled(false);
			findViewById(R.id.btnDecrypt).setEnabled(false);
		}
	}
}
